#!/usr/bin/env python
"""
This script is responsible for making sure the database is ready to store the next scan
It figures out the number of the next scan and removes all traces of it from the database
"""

def dotprogress():
	from sys import stdout
	print ".",
	stdout.flush()
def cleartables(scan):
	print "Clearing cached results from scan #%s"%scan
	global db
	cursor=db.cursor()
	cursor.execute("delete from host_stats where scanid='%s'"%scan)
	dotprogress()
	cursor.execute("delete from hosts where lastscan='%s'"%scan)
	dotprogress()
	cursor.execute("delete from path_stats where scanid='%s'"%scan)
	dotprogress()
	cursor.execute("delete from paths where lastscan='%s'"%scan)
	dotprogress()
	cursor.execute("delete from file_stats where scanid='%s'"%scan)
	dotprogress()
	cursor.execute("delete from files where lastscan='%s'"%scan)
	dotprogress()
	cursor.execute("delete file_stats_single from file_stats_single left join files on files.id=file_stats_single.fileid where files.id is null")
	dotprogress()
	
	# automatically gets deleted because of the foreign keys on searches/searchresults
	#cursor.execute("delete from searchresults where searchid in (select id from searches where searches.scanid='%s' or searches.scanid='%s')"%(scan,nextscan))
	#dotprogress()
	
	# delete searches from the deleted scan
	cursor.execute("lock tables searches write")
	cursor.execute("delete from searches where scanid='%s'"%scan)
	cursor.execute("unlock tables")
	dotprogress()

	# remove offline searches, because offline files may have been pruned
	cursor.execute("lock tables searches write")
	cursor.execute("delete from searches where searches.offline=1 and numresults is not null")
	cursor.execute("unlock tables")
	dotprogress()
	
	print
	
print "Connecting to database"
import database
db=database.getConnection()
cursor=db.cursor()

nextscan=database.getNextScan(cursor)
cleartables(nextscan)

# record the time of the scan
print "Starting scan %s"%nextscan
cursor.execute("delete from scans where id=%s",nextscan)
cursor.execute("insert into scans (id,time) values (%s,now())",nextscan)
